package com.lhd.interceptor;

import com.lhd.utils.JwtUtil;
import com.lhd.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getMethod() + request.getRequestURL());
        try {
            String token = request.getHeader("Authorization");
            //去redis中找一样的
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            String redisToken = ops.get("token");
            if (redisToken == null) throw new Exception();
            //验证合法性
            Map<String, Object> claims = jwtUtil.parseToken(token);
            //将信息存入本地
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
